import { makeAutoObservable } from 'mobx';

type Config = {
    theme: string;
    radius: number;
};

class AppStore {
    loading: boolean = false;

    config: Config = {
        theme: 'zinc',
        radius: 0.5,
    };

    mode: string = 'system';

    menuPosition: string = 'left';

    isCollapsed: boolean = false;

    constructor() {
        makeAutoObservable(this);
        try {
            const localConfig = JSON.parse(localStorage.getItem('config')!);
            const localMode = localStorage.getItem('mode')!;
            this.isCollapsed = localStorage.getItem('isCollapsed') === 'true';
            this.menuPosition = localStorage.getItem('menuPosition')!;

            if (localConfig) {
                this.config = localConfig;
            }
            if (['dark', 'light', 'system'].includes(localMode)) {
                this.mode = localMode;
            } else {
                this.mode = 'system';
            }
        } catch (error) {
            this.config = {
                theme: 'zinc',
                radius: 0.5,
            };
            this.mode = 'system';
        }
        localStorage.setItem('config', JSON.stringify(this.config));
        localStorage.setItem('mode', this.mode);
    }

    setLoading(loading: boolean) {
        this.loading = loading;
    }

    setConfig(config: Config) {
        this.config = config;
        localStorage.setItem('config', JSON.stringify(this.config));
    }

    setMode(mode: string) {
        switch (mode) {
            case 'dark': {
                document.documentElement.classList.add('dark');
                document.documentElement.style.colorScheme = 'dark';
                break;
            }
            case 'light': {
                document.documentElement.classList.remove('dark');
                document.documentElement.style.colorScheme = 'light';
                break;
            }
            case 'system': {
                if (window.matchMedia('(prefers-color-scheme: dark)').matches) {
                    document.documentElement.classList.add('dark');
                    document.documentElement.style.colorScheme = 'dark';
                } else {
                    document.documentElement.classList.remove('dark');
                    document.documentElement.style.colorScheme = 'light';
                }
                break;
            }
            default: {
                break;
            }
        }
        localStorage.setItem('mode', mode);
        this.mode = mode;
    }

    setMenuPosition(menuPosition: string) {
        this.menuPosition = menuPosition;
        localStorage.setItem('menuPosition', this.menuPosition);
    }

    setIsCollapsed(isCollapsed: boolean) {
        this.isCollapsed = isCollapsed;
        localStorage.setItem('isCollapsed', String(this.isCollapsed));
    }
}

const appStore = new AppStore();

export default appStore;
